#include<iostream>
#include<unistd.h>
#include<cstring>
#include<sys/wait.h>
using namespace std;
int main()
{
    //先创建管道
   int fd[2]={0};
   int pip=pipe(fd);
   if(pip==-1)
   {
    perror("创建管道失败\n");
    return 1;
   }
   pid_t pid=fork();
   if(pid==0)
   {
    //child
    close(fd[0]);//关闭读端
    int count=10;
    char msg[]="i am child process...";
    while(count--)
    {
        write(fd[1],msg,strlen(msg));
        sleep(1);
    }
   
    close(fd[1]);
    exit(0);
   }
   close(fd[1]);
   char buffer[1024];
   memset(buffer,0,sizeof(buffer));
   while(1)
   {
    size_t n=read(fd[0],buffer,sizeof(buffer));
    if(n>0)
    {
        cout<<"child send to father: ";
        buffer[n]=0;
        cout<<buffer<<endl;
    }
    else if(n==0)
    {
        cout<<"child is end";
        break;
    }
    else
    {
        cout<<"read error";
        break;
    }
    
   }
   close(fd[0]);
   waitpid(pid,NULL,0);
   exit(0);
}